const { sequelize } = require('../config/database');
const UserAiConversation = require('../models/UserAiConversation');

async function migrateAvatarField() {
    try {
        console.log('🔄 开始迁移头像字段数据...');
        
        // 测试数据库连接
        await sequelize.authenticate();
        console.log('✅ 数据库连接成功');
        
        // 同步数据库结构（添加新字段）
        await sequelize.sync({ alter: true });
        console.log('✅ 数据库结构更新完成');
        
        // 查找所有需要迁移的记录
        const conversations = await UserAiConversation.findAll({
            where: {
                ai_avatar: [null, '']
            }
        });
        
        console.log(`📊 找到 ${conversations.length} 条需要迁移的记录`);
        
        let migratedCount = 0;
        
        // 批量迁移数据
        for (const conversation of conversations) {
            const avatarUrl = conversation.conversation_data?.metadata?.avatar_url;
            
            if (avatarUrl && avatarUrl.trim() !== '') {
                await conversation.update({
                    ai_avatar: avatarUrl
                });
                migratedCount++;
                console.log(`✅ 迁移对话 ${conversation.ai_person_id}: ${avatarUrl}`);
            }
        }
        
        console.log(`🎉 迁移完成! 共迁移 ${migratedCount} 条记录`);
        
    } catch (error) {
        console.error('❌ 迁移失败:', error);
        process.exit(1);
    } finally {
        await sequelize.close();
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    migrateAvatarField()
        .then(() => {
            console.log('脚本执行完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('脚本执行失败：', error);
            process.exit(1);
        });
}

module.exports = migrateAvatarField; 